<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>预约管理-图书馆座位预约管理系统</title>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <style>
        /* 原有样式保持不变 */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
        }

        body {
            background-color: #f0f8ff;
            min-height: 100vh;
            color: #333;
            display: flex;
        }

        /* 左侧导航栏样式 */
        .sidebar {
            width: 250px;
            background: #1a2a6c;
            color: white;
            height: 100vh;
            position: fixed;
            overflow-y: auto;
            transition: width 0.3s ease;
        }

        .sidebar.collapsed {
            width: 70px;
        }

        .sidebar-header {
            padding: 20px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .logo {
            display: flex;
            align-items: center;
            gap: 10px;
            font-size: 1.2rem;
            font-weight: bold;
            white-space: nowrap;
            overflow: hidden;
        }

        .logo i {
            font-size: 1.5rem;
            min-width: 24px;
        }

        .sidebar-nav ul {
            list-style: none;
            padding: 0;
        }

        .nav-item {
            margin: 5px 0;
        }

        .nav-link {
            display: flex;
            align-items: center;
            gap: 15px;
            padding: 15px 20px;
            color: white;
            text-decoration: none;
            transition: background-color 0.3s;
            white-space: nowrap;
            overflow: hidden;
        }

        .nav-link:hover, .nav-item.active .nav-link {
            background-color: rgba(255, 255, 255, 0.1);
        }

        .nav-link i {
            width: 20px;
            text-align: center;
            font-size: 1.1rem;
        }

        /* 主内容区域 */
        .main-content {
            flex: 1;
            margin-left: 250px;
            display: flex;
            flex-direction: column;
            transition: margin-left 0.3s ease;
        }

        .main-content.expanded {
            margin-left: 70px;
        }

        /* 顶部导航栏 */
        .top-navbar {
            background-color: white;
            padding: 15px 30px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .navbar-left {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .menu-toggle {
            background: none;
            border: none;
            font-size: 1.2rem;
            cursor: pointer;
            color: #1a2a6c;
            padding: 5px;
            border-radius: 4px;
            transition: background-color 0.3s;
        }

        .menu-toggle:hover {
            background-color: #f0f0f0;
        }

        .page-title {
            color: #1a2a6c;
            font-size: 1.5rem;
        }

        .navbar-right {
            display: flex;
            align-items: center;
            gap: 20px;
        }

        .search-box {
            position: relative;
        }

        .search-box input {
            padding: 8px 35px 8px 15px;
            border: 1px solid #ddd;
            border-radius: 4px;
            width: 250px;
        }

        .search-box i {
            position: absolute;
            right: 12px;
            top: 50%;
            transform: translateY(-50%);
            color: #888;
        }

        .user-profile {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .user-profile img {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            object-fit: cover;
            background-color: #1a73e8;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: bold;
        }

        /* 预约管理内容区域 */
        .booking-management {
            padding: 25px;
            flex: 1;
        }

        .toolbar {
            display: flex;
            justify-content: space-between;
            margin-bottom: 20px;
            flex-wrap: wrap;
            gap: 15px;
        }

        .filter-container {
            display: flex;
            gap: 15px;
            flex-wrap: wrap;
        }

        .filter-item {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .filter-item label {
            font-weight: 500;
            white-space: nowrap;
        }

        .form-control {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            min-width: 150px;
        }

        .date-separator {
            margin: 0 5px;
        }

        .action-buttons {
            display: flex;
            gap: 10px;
        }

        .btn {
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 8px;
            font-weight: 500;
            transition: all 0.3s;
        }

        .btn-primary {
            background: #1a73e8;
            color: white;
        }

        .btn-primary:hover {
            background: #0d62d9;
        }

        .btn-outline {
            background: transparent;
            border: 1px solid #1a73e8;
            color: #1a73e8;
        }

        .btn-outline:hover {
            background: #1a73e8;
            color: white;
        }

        .btn-success {
            background: #2ecc71;
            color: white;
        }

        .btn-success:hover {
            background: #27ae60;
        }

        .btn-danger {
            background: #e74c3c;
            color: white;
        }

        .btn-danger:hover {
            background: #c0392b;
        }

        .btn-sm {
            padding: 6px 12px;
            font-size: 14px;
        }

        /* 卡片样式 */
        .card {
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            margin-bottom: 25px;
        }

        .card-header {
            padding: 20px;
            border-bottom: 1px solid #eee;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .card-header h3 {
            font-size: 18px;
            font-weight: 600;
            color: #1a2a6c;
        }

        .table-info {
            color: #7f8c8d;
            font-size: 14px;
        }

        .table-container {
            overflow-x: auto;
        }

        .data-table {
            width: 100%;
            border-collapse: collapse;
        }

        .data-table th, .data-table td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #eee;
        }

        .data-table th {
            background: #1a2a6c;
            color: white;
            font-weight: 600;
        }

        .data-table tr:hover {
            background: #f8f9fa;
        }

        .status-badge {
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: 500;
        }

        .status-badge.pending {
            background: rgba(241, 196, 15, 0.2);
            color: #f39c12;
        }

        .status-badge.active {
            background: rgba(46, 204, 113, 0.2);
            color: #27ae60;
        }

        .status-badge.completed {
            background: rgba(52, 152, 219, 0.2);
            color: #2980b9;
        }

        .status-badge.canceled {
            background: rgba(231, 76, 60, 0.2);
            color: #c0392b;
        }

        .status-badge.expired {
            background: rgba(149, 165, 166, 0.2);
            color: #7f8c8d;
        }

        .action-btn {
            background: none;
            border: none;
            cursor: pointer;
            padding: 5px;
            margin: 0 2px;
            border-radius: 4px;
            transition: all 0.3s;
            color: #e74c3c;
        }

        .action-btn:hover {
            background: rgba(231, 76, 60, 0.1);
        }

        .action-btn:disabled {
            color: #ccc;
            cursor: not-allowed;
        }

        .action-btn:disabled:hover {
            background: none;
        }

        .card-footer {
            padding: 15px 20px;
            border-top: 1px solid #eee;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .pagination ul {
            display: flex;
            list-style: none;
            gap: 5px;
        }

        .pagination a {
            display: block;
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            text-decoration: none;
            color: #1a73e8;
            transition: all 0.3s;
        }

        .pagination a.active, .pagination a:hover {
            background: #1a73e8;
            color: white;
            border-color: #1a73e8;
        }

        .pagination a.disabled {
            color: #ccc;
            cursor: not-allowed;
            pointer-events: none;
        }

        /* 模态框样式 */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.7);
            z-index: 1000;
            overflow: auto;
        }

        .modal.show {
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .modal-content {
            background-color: white;
            margin: 5% auto;
            padding: 0;
            border-radius: 12px;
            width: 90%;
            max-width: 600px;
            max-height: 90vh;
            overflow-y: auto;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
            animation: modalFade 0.3s;
        }

        @keyframes modalFade {
            from {opacity: 0; transform: translateY(-50px);}
            to {opacity: 1; transform: translateY(0);}
        }

        .modal-header {
            background: #1a2a6c;
            color: white;
            padding: 20px;
            border-radius: 12px 12px 0 0;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .modal-header h3 {
            margin: 0;
            font-size: 20px;
        }

        .close-btn {
            background: none;
            border: none;
            font-size: 24px;
            cursor: pointer;
            color: white;
        }

        .close-btn:hover {
            color: #ddd;
        }

        .modal-body {
            padding: 20px;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: #1a2a6c;
        }

        .form-group input, .form-group select, .form-group textarea {
            width: 100%;
            padding: 10px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 16px;
        }

        .form-row {
            display: flex;
            gap: 15px;
        }

        .form-row .form-group {
            flex: 1;
        }

        .modal-footer {
            padding: 15px 20px;
            border-top: 1px solid #eee;
            display: flex;
            justify-content: flex-end;
            gap: 10px;
        }

        /* 新增样式 */
        .date-hint {
            font-size: 12px;
            color: #7f8c8d;
            margin-top: 5px;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .sidebar {
                width: 70px;
            }

            .sidebar:not(.collapsed) .logo span,
            .sidebar:not(.collapsed) .nav-link span {
                display: none;
            }

            .main-content {
                margin-left: 70px;
            }

            .toolbar {
                flex-direction: column;
                align-items: flex-start;
            }

            .filter-container {
                width: 100%;
            }

            .action-buttons {
                width: 100%;
                justify-content: flex-start;
            }

            .form-row {
                flex-direction: column;
                gap: 0;
            }
        }
    </style>
</head>
<body>
<!-- 左侧导航栏 -->
<aside class="sidebar">
    <div class="sidebar-header">
        <h1 class="logo">
            <span>图书馆座位预约管理系统</span>
        </h1>
    </div>
    <nav class="sidebar-nav">
        <ul>
            <li class="nav-item">
                <a href="index.html" class="nav-link">
                    <i class="fa fa-home"></i>
                    <span>首页</span>
                </a>
            </li>
            <li class="nav-item">
                <a href="seat-management1.html" class="nav-link">
                    <i class="fa fa-th-large"></i>
                    <span>座位管理</span>
                </a>
            </li>
            <li class="nav-item active">
                <a href="booking-management.html" class="nav-link">
                    <i class="fa fa-calendar-check-o"></i>
                    <span>预约管理</span>
                </a>
            </li>
            <li class="nav-item">
                <a href="user-management1.html" class="nav-link">
                    <i class="fa fa-users"></i>
                    <span>用户管理</span>
                </a>
            </li>
        </ul>
    </nav>
</aside>

<!-- 主内容区域 -->
<div class="main-content">
    <!-- 顶部导航栏 -->
    <header class="top-navbar">
        <div class="navbar-left">
            <button class="menu-toggle" id="menuToggle">
                <i class="fa fa-bars"></i>
            </button>
            <h2 class="page-title">预约管理</h2>
        </div>
        <div class="navbar-right">
            <div class="search-box">
                <input type="text" placeholder="搜索预约..." id="searchInput">
                <i class="fa fa-search"></i>
            </div>
            <div class="user-profile">
                <img src="manager.png" alt="管理员头像">
                <span>管理员</span>
            </div>
        </div>
    </header>

    <div class="booking-management">
        <div class="toolbar">
            <div class="filter-container">
                <div class="filter-item">
                    <label>预约状态:</label>
                    <select class="form-control" id="statusFilter">
                        <option value="all">全部状态</option>
                        <option value="pending_fulfillment">待履约</option>
                        <option value="fulfilled">已履约</option>
                        <option value="cancelled">已取消</option>
                        <option value="breach">违约</option>
                    </select>
                </div>
                <div class="filter-item">
                    <label>用户名:</label>
                    <select class="form-control" id="userFilter">
                        <option value="all">全部用户</option>
                    </select>
                </div>
                <div class="filter-item">
                    <label>座位ID:</label>
                    <select class="form-control" id="seatFilter">
                        <option value="all">全部座位</option>
                    </select>
                </div>
                <div class="filter-item">
                    <label>日期范围:</label>
                    <input type="date" class="form-control" id="startDate">
                    <span class="date-separator">至</span>
                    <input type="date" class="form-control" id="endDate">
                    <div class="date-hint">只能查询当天及之前的预约记录</div>
                </div>
                <div class="filter-item">
                    <button class="btn btn-outline" id="clearFilters">
                        <i class="fa fa-times"></i> 清除筛选
                    </button>
                </div>
            </div>
            <div class="action-buttons">
                <button class="btn btn-primary" id="addBookingBtn">
                    <i class="fa fa-plus"></i> 新增预约
                </button>
                <button class="btn btn-outline" id="refreshBtn">
                    <i class="fa fa-refresh"></i> 刷新
                </button>
            </div>
        </div>

        <!-- 预约列表 -->
        <div class="card">
            <div class="card-header">
                <h3>预约列表</h3>
                <div class="table-info">
                    <span id="tableInfo">正在加载预约记录...</span>
                </div>
            </div>
            <div class="table-container">
                <table class="data-table" id="bookingTable">
                    <thead>
                    <tr>
                        <th>预约ID</th>
                        <th>用户名</th>
                        <th>座位ID</th>
                        <th>预约时间</th>
                        <th>开始时间</th>
                        <th>结束时间</th>
                        <th>状态</th>
                        <th>签到时间</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody id="bookingTableBody">
                    </tbody>
                </table>
            </div>
            <div class="card-footer">
                <div class="pagination">
                    <ul id="paginationList">
                    </ul>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 预约模态框 -->
<div class="modal" id="bookingModal">
    <div class="modal-content">
        <div class="modal-header">
            <h3 id="modalTitle">新增预约</h3>
            <button class="close-btn" id="closeModal">&times;</button>
        </div>
        <div class="modal-body">
            <form id="bookingForm">
                <div class="form-row">
                    <div class="form-group">
                        <label for="username">用户名</label>
                        <input type="text" id="username" required>
                    </div>
                    <div class="form-group">
                        <label for="seatId">座位ID</label>
                        <input type="number" id="seatId" required>
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label for="date">预约日期</label>
                        <input type="date" id="date" required>
                    </div>
                    <div class="form-group">
                        <label for="areaname">区域名称</label>
                        <input type="text" id="areaname" required>
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label for="startTime">开始时间</label>
                        <input type="time" id="startTime" required>
                    </div>
                    <div class="form-group">
                        <label for="endTime">结束时间</label>
                        <input type="time" id="endTime" required>
                    </div>
                </div>
                <div class="form-group">
                    <label for="durationHours">持续小时数</label>
                    <input type="number" id="durationHours" step="0.5" min="0.5" max="24" required>
                </div>
            </form>
        </div>
        <div class="modal-footer">
            <button class="btn btn-outline" id="cancelBtn">取消</button>
            <button class="btn btn-primary" id="saveBtn">保存</button>
        </div>
    </div>
</div>

<!-- 操作确认模态框 -->
<div class="modal" id="confirmModal">
    <div class="modal-content">
        <div class="modal-header">
            <h3 id="confirmModalTitle">确认操作</h3>
            <button class="close-btn" id="closeConfirmModal">&times;</button>
        </div>
        <div class="modal-body">
            <p id="confirmMessage">确定要执行此操作吗？</p>
        </div>
        <div class="modal-footer">
            <button class="btn btn-outline" id="cancelConfirmBtn">取消</button>
            <button class="btn btn-danger" id="confirmActionBtn">确认删除</button>
        </div>
    </div>
</div>

<script>
    // 菜单切换功能
    const menuToggle = document.getElementById('menuToggle');
    const sidebar = document.querySelector('.sidebar');
    const mainContent = document.querySelector('.main-content');

    if (menuToggle) {
        menuToggle.addEventListener('click', function() {
            sidebar.classList.toggle('collapsed');
            mainContent.classList.toggle('expanded');
        });
    }

    // API基础URL
    const API_BASE_URL = 'http://localhost:8080/api';

    // 预约数据 - 从后端API获取
    let bookings = [];

    // DOM元素
    const bookingTableBody = document.getElementById('bookingTableBody');
    const bookingModal = document.getElementById('bookingModal');
    const confirmModal = document.getElementById('confirmModal');
    const bookingForm = document.getElementById('bookingForm');
    const addBookingBtn = document.getElementById('addBookingBtn');
    const saveBtn = document.getElementById('saveBtn');
    const closeModal = document.getElementById('closeModal');
    const cancelBtn = document.getElementById('cancelBtn');
    const closeConfirmModal = document.getElementById('closeConfirmModal');
    const cancelConfirmBtn = document.getElementById('cancelConfirmBtn');
    const confirmActionBtn = document.getElementById('confirmActionBtn');
    const searchInput = document.getElementById('searchInput');
    const statusFilter = document.getElementById('statusFilter');
    const userFilter = document.getElementById('userFilter');
    const seatFilter = document.getElementById('seatFilter');
    const startDate = document.getElementById('startDate');
    const endDate = document.getElementById('endDate');
    const refreshBtn = document.getElementById('refreshBtn');
    const clearFiltersBtn = document.getElementById('clearFilters');
    const paginationList = document.getElementById('paginationList');
    const tableInfo = document.getElementById('tableInfo');
    const confirmMessage = document.getElementById('confirmMessage');
    const confirmModalTitle = document.getElementById('confirmModalTitle');

    // 分页相关变量
    let currentPage = 1;
    const itemsPerPage = 10;
    let filteredBookings = [];

    // 当前操作变量
    let currentAction = null;
    let currentReservationId = null;

    // 初始化页面
    document.addEventListener('DOMContentLoaded', function() {
        // 设置日期输入框的默认值 - 只能选择当天及之前的日期
        const today = new Date();
        const defaultStartDate = new Date(today);
        defaultStartDate.setDate(today.getDate() - 7); // 一周前
        startDate.value = formatDate(defaultStartDate);
        endDate.value = formatDate(today);

        // 设置日期输入框的最大值为今天
        startDate.max = formatDate(today);
        endDate.max = formatDate(today);

        loadBookings();
        setupEventListeners();
    });

    // 设置事件监听器
    function setupEventListeners() {
        // 模态框控制
        addBookingBtn.addEventListener('click', openAddModal);
        closeModal.addEventListener('click', closeBookingModal);
        cancelBtn.addEventListener('click', closeBookingModal);
        saveBtn.addEventListener('click', saveBooking);

        // 确认模态框控制
        closeConfirmModal.addEventListener('click', closeConfirmModalFunc);
        cancelConfirmBtn.addEventListener('click', closeConfirmModalFunc);
        confirmActionBtn.addEventListener('click', executeAction);

        // 筛选和搜索
        searchInput.addEventListener('input', filterBookings);
        statusFilter.addEventListener('change', filterBookings);
        userFilter.addEventListener('change', filterBookings);
        seatFilter.addEventListener('change', filterBookings);
        startDate.addEventListener('change', filterBookings);
        endDate.addEventListener('change', filterBookings);

        // 刷新按钮
        refreshBtn.addEventListener('click', loadBookings);

        // 清除筛选按钮
        clearFiltersBtn.addEventListener('click', clearFilters);
    }

    // 清除所有筛选条件
    function clearFilters() {
        statusFilter.value = 'all';
        userFilter.value = 'all';
        seatFilter.value = 'all';
        searchInput.value = '';

        // 重置日期为默认值
        const today = new Date();
        const defaultStartDate = new Date(today);
        defaultStartDate.setDate(today.getDate() - 7);
        startDate.value = formatDate(defaultStartDate);
        endDate.value = formatDate(today);

        filterBookings();
    }

    // 从后端API获取预约数据
    async function loadBookings() {
        try {
            const response = await fetch(`${API_BASE_URL}/reservations/all`);
            if (!response.ok) {
                throw new Error('获取预约数据失败');
            }
            const reservationList = await response.json();
            console.log('reservationList:', reservationList);

            // 转换数据格式以匹配前端显示需求
            bookings = reservationList.map((reservation, index) => ({
                id: reservation.id,
                index: index + 1,
                username: reservation.username,
                seatId: reservation.seatId,
                reservationTime: formatDateTime(reservation.createdAt),
                startTime: formatDateTime(reservation.actualCheckinTime),
                endTime: formatDateTime(reservation.actualCheckoutTime),
                status: reservation.status,
                checkinTime: reservation.actualCheckinTime ? formatDateTime(reservation.actualCheckinTime) : '未签到',
                notes: reservation.notes || ''
            }));

            console.log('bookings:', bookings);

            // 初始化筛选后的数据
            filteredBookings = [...bookings];

            // 更新用户和座位筛选下拉框
            updateFilterOptions();

            renderBookings();
            updatePagination();

            document.getElementById('tableInfo').textContent = `共 ${filteredBookings.length} 条预约记录`;
        } catch (error) {
            console.error('Error fetching bookings:', error);
            alert('获取预约数据失败: ' + error.message);
        }
    }

    // 更新筛选下拉框选项
    function updateFilterOptions() {
        // 更新用户筛选下拉框
        const userSet = new Set();
        bookings.forEach(booking => userSet.add(booking.username));

        userFilter.innerHTML = '<option value="all">全部用户</option>';
        userSet.forEach(user => {
            const option = document.createElement('option');
            option.value = user;
            option.textContent = user;
            userFilter.appendChild(option);
        });

        // 更新座位筛选下拉框
        const seatSet = new Set();
        bookings.forEach(booking => seatSet.add(booking.seatId));

        seatFilter.innerHTML = '<option value="all">全部座位</option>';
        seatSet.forEach(seat => {
            const option = document.createElement('option');
            option.value = seat;
            option.textContent = seat;
            seatFilter.appendChild(option);
        });
    }

    // 渲染预约列表
    function renderBookings() {
        bookingTableBody.innerHTML = '';

        // 计算当前页显示的数据
        const startIndex = (currentPage - 1) * itemsPerPage;
        const endIndex = Math.min(startIndex + itemsPerPage, filteredBookings.length);
        const currentBookings = filteredBookings.slice(startIndex, endIndex);

        if (currentBookings.length === 0) {
            bookingTableBody.innerHTML = `
                <tr>
                    <td colspan="9" style="text-align: center; padding: 30px;">
                        <i class="fa fa-inbox" style="font-size: 48px; color: #ddd; margin-bottom: 10px;"></i>
                        <p>暂无预约数据</p>
                    </td>
                </tr>
            `;
            return;
        }

        currentBookings.forEach(booking => {
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${booking.id}</td>
                <td>${booking.username}</td>
                <td>${booking.seatId}</td>
                <td>${booking.reservationTime}</td>
                <td>${booking.startTime}</td>
                <td>${booking.endTime}</td>
                <td>
                    <span class="status-badge ${getStatusClass(booking.status)}">
                        ${getStatusText(booking.status)}
                    </span>
                </td>
                <td>${booking.checkinTime}</td>
                <td>
                    <button class="action-btn delete" data-id="${booking.id}"
                    ${!canDelete(booking.status) ? 'disabled' : ''}>
                    <i class="fa fa-trash"></i> 取消预约
                    </button>
                </td>
            `;
            bookingTableBody.appendChild(row);
        });

        // 更新表格信息
        tableInfo.textContent = `显示第 ${startIndex + 1} 到 ${endIndex} 条，共 ${filteredBookings.length} 条记录`;

        // 绑定行内按钮事件
        addRowEventListeners();
    }

    function getStatusText(status) {
        const statusMap = {
            'pending_fulfillment': '待履约',
            'fulfilled': '已履约',
            'cancelled': '已取消',
            'breach': '违约'
        };
        return statusMap[status] || status;
    }

    function getStatusClass(status) {
        const classMap = {
            'pending_fulfillment': 'pending',
            'fulfilled': 'completed',
            'cancelled': 'canceled',
            'breach': 'expired'
        };
        return classMap[status] || 'pending';
    }

    function canDelete(status) {
        // 只有特定状态可以删除
        const deletableStatuses = ['pending_fulfillment', 'fulfilled', 'cancelled', 'breach'];
        return deletableStatuses.includes(status);
    }

    // 添加行内按钮事件监听器
    function addRowEventListeners() {
        // 删除按钮
        document.querySelectorAll('.action-btn.delete:not([disabled])').forEach(btn => {
            btn.addEventListener('click', function() {
                const id = this.getAttribute('data-id');
                showConfirmModal('确认删除', `确定要删除此预约吗？此操作不可撤销。`, 'delete', id);
            });
        });
    }

    // 显示确认模态框
    function showConfirmModal(title, message, action, reservationId) {
        confirmModalTitle.textContent = title;
        confirmMessage.textContent = message;
        currentAction = action;
        currentReservationId = reservationId;
        confirmModal.classList.add('show');
    }

    // 执行操作
    async function executeAction() {
        if (!currentAction || !currentReservationId) return;

        try {
            let response;
            const userId = "admin"; // 临时使用管理员ID，实际应从登录信息获取

            switch (currentAction) {
                case 'delete':
                    response = await fetch(`${API_BASE_URL}/reservations/${currentReservationId}/cancel`, {
                        method: 'POST',
                        headers: {
                            'userId': userId,
                            'Content-Type': 'application/json'
                        }
                    });
                    break;
            }

            if (!response.ok) {
                const errorText = await response.text();
                throw new Error(errorText);
            }

            const result = await response.json();
            closeConfirmModalFunc();
            alert('操作成功: ' + result.message);
            loadBookings(); // 重新加载数据
        } catch (error) {
            console.error(`Error executing ${currentAction}:`, error);
            alert('操作失败: ' + error.message);
        }
    }

    // 打开新增预约模态框
    function openAddModal() {
        document.getElementById('modalTitle').textContent = '新增预约';
        bookingForm.reset();
        currentReservationId = null;

        // 设置默认值
        const today = new Date();
        document.getElementById('date').value = formatDate(today);

        // 设置默认开始时间为当前时间
        const now = new Date();
        document.getElementById('startTime').value = formatTime(now);

        // 设置默认结束时间为2小时后
        const endTime = new Date(now.getTime() + 2 * 60 * 60 * 1000);
        document.getElementById('endTime').value = formatTime(endTime);

        // 设置默认持续时间为2小时
        document.getElementById('durationHours').value = 2;

        bookingModal.classList.add('show');
    }

    // 保存预约
    async function saveBooking() {
        const username = document.getElementById('username').value;
        const seatId = document.getElementById('seatId').value;
        const date = document.getElementById('date').value;
        const areaname = document.getElementById('areaname').value;
        const startTime = document.getElementById('startTime').value;
        const endTime = document.getElementById('endTime').value;
        const durationHours = document.getElementById('durationHours').value;

        if (!username || !seatId || !date || !areaname || !startTime || !endTime || !durationHours) {
            alert('请填写所有必填字段');
            return;
        }

        try {
            // 构建符合ReservationRequest格式的数据
            const requestData = {
                username: username,
                seatId: parseInt(seatId),
                date: date,
                areaname: areaname,
                startTime: startTime + ":00", // 添加秒部分
                endTime: endTime + ":00", // 添加秒部分
                durationHours: parseFloat(durationHours)
            };

            console.log('Sending reservation data:', requestData);

            const response = await fetch(`${API_BASE_URL}/reservations/reserve`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(requestData)
            });

            const result = await response.json();

            if (!response.ok) {
                throw new Error(result.message || '预约失败');
            }

            if (result.success) {
                closeBookingModal();
                alert('预约成功，预约ID: ' + result.reservationId);
                loadBookings(); // 重新加载数据
            } else {
                throw new Error(result.message);
            }
        } catch (error) {
            console.error('Error creating booking:', error);
            alert('预约失败: ' + error.message);
        }
    }

    // 关闭预约模态框
    function closeBookingModal() {
        bookingModal.classList.remove('show');
    }

    // 关闭确认模态框
    function closeConfirmModalFunc() {
        confirmModal.classList.remove('show');
        currentAction = null;
        currentReservationId = null;
    }

    // 筛选预约
    function filterBookings() {
        const searchTerm = searchInput.value.toLowerCase();
        const statusValue = statusFilter.value;
        const userValue = userFilter.value;
        const seatValue = seatFilter.value;
        const startDateValue = startDate.value;
        const endDateValue = endDate.value;

        filteredBookings = bookings.filter(booking => {
            // 搜索条件
            const matchesSearch = !searchTerm ||
                booking.id.toString().toLowerCase().includes(searchTerm) ||
                booking.username.toLowerCase().includes(searchTerm) ||
                booking.seatId.toString().toLowerCase().includes(searchTerm);

            // 状态条件
            const matchesStatus = statusValue === 'all' || booking.status === statusValue;

            // 用户条件
            const matchesUser = userValue === 'all' || booking.username === userValue;

            // 座位条件
            const matchesSeat = seatValue === 'all' || booking.seatId.toString() === seatValue;

            // 日期范围条件
            let matchesDate = true;
            if (startDateValue && endDateValue) {
                const bookingDate = new Date(booking.reservationTime.split(' ')[0]);
                const start = new Date(startDateValue);
                const end = new Date(endDateValue);
                end.setHours(23, 59, 59, 999); // 设置为当天的最后一刻
                matchesDate = bookingDate >= start && bookingDate <= end;
            }

            return matchesSearch && matchesStatus && matchesUser && matchesSeat && matchesDate;
        });

        // 重置到第一页
        currentPage = 1;

        renderBookings();
        updatePagination();
    }

    // 更新分页
    function updatePagination() {
        paginationList.innerHTML = '';

        const totalPages = Math.ceil(filteredBookings.length / itemsPerPage);

        if (totalPages <= 1) {
            return;
        }

        // 上一页按钮
        const prevLi = document.createElement('li');
        prevLi.innerHTML = `<a href="#" id="prevPage" class="${currentPage === 1 ? 'disabled' : ''}">上一页</a>`;
        paginationList.appendChild(prevLi);

        // 页码按钮
        const maxVisiblePages = 5;
        let startPage = Math.max(1, currentPage - Math.floor(maxVisiblePages / 2));
        let endPage = Math.min(totalPages, startPage + maxVisiblePages - 1);

        // 调整起始页码，确保显示maxVisiblePages个页码
        if (endPage - startPage + 1 < maxVisiblePages) {
            startPage = Math.max(1, endPage - maxVisiblePages + 1);
        }

        // 第一页和省略号
        if (startPage > 1) {
            const firstLi = document.createElement('li');
            firstLi.innerHTML = `<a href="#" data-page="1">1</a>`;
            paginationList.appendChild(firstLi);

            if (startPage > 2) {
                const ellipsisLi = document.createElement('li');
                ellipsisLi.innerHTML = `<a href="#" class="disabled">...</a>`;
                paginationList.appendChild(ellipsisLi);
            }
        }

        // 页码
        for (let i = startPage; i <= endPage; i++) {
            const pageLi = document.createElement('li');
            pageLi.innerHTML = `<a href="#" data-page="${i}" class="${i === currentPage ? 'active' : ''}">${i}</a>`;
            paginationList.appendChild(pageLi);
        }

        // 最后一页和省略号
        if (endPage < totalPages) {
            if (endPage < totalPages - 1) {
                const ellipsisLi = document.createElement('li');
                ellipsisLi.innerHTML = `<a href="#" class="disabled">...</a>`;
                paginationList.appendChild(ellipsisLi);
            }

            const lastLi = document.createElement('li');
            lastLi.innerHTML = `<a href="#" data-page="${totalPages}">${totalPages}</a>`;
            paginationList.appendChild(lastLi);
        }

        // 下一页按钮
        const nextLi = document.createElement('li');
        nextLi.innerHTML = `<a href="#" id="nextPage" class="${currentPage === totalPages ? 'disabled' : ''}">下一页</a>`;
        paginationList.appendChild(nextLi);

        // 添加分页事件监听器
        addPaginationEventListeners();
    }

    // 添加分页事件监听器
    function addPaginationEventListeners() {
        // 上一页
        const prevPageBtn = document.getElementById('prevPage');
        if (prevPageBtn) {
            prevPageBtn.addEventListener('click', function(e) {
                e.preventDefault();
                if (currentPage > 1) {
                    currentPage--;
                    renderBookings();
                    updatePagination();
                }
            });
        }

        // 下一页
        const nextPageBtn = document.getElementById('nextPage');
        if (nextPageBtn) {
            nextPageBtn.addEventListener('click', function(e) {
                e.preventDefault();
                const totalPages = Math.ceil(filteredBookings.length / itemsPerPage);
                if (currentPage < totalPages) {
                    currentPage++;
                    renderBookings();
                    updatePagination();
                }
            });
        }

        // 页码
        document.querySelectorAll('[data-page]').forEach(link => {
            link.addEventListener('click', function(e) {
                e.preventDefault();
                if (!this.classList.contains('disabled')) {
                    const page = parseInt(this.getAttribute('data-page'));
                    if (page !== currentPage) {
                        currentPage = page;
                        renderBookings();
                        updatePagination();
                    }
                }
            });
        });
    }

    // 工具函数
    function formatDate(date) {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
    }

    function formatTime(date) {
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        return `${hours}:${minutes}`;
    }

    function formatDateTime(iso) {
        if (!iso) return '未知';

        const date = new Date(iso);
        if (isNaN(date.getTime())) return '未知';

        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');

        return `${year}-${month}-${day} ${hours}:${minutes}`;
    }
</script>
</body>
</html>